package model

import (
	"blog/app/common"
	"blog/app/utils"
	"log"
)

type Config struct {
	Name      string `json:"name"`
	Password  string `json:"password"`
	Signature string `json:"signature"`
	Contact   string `json:"contact"`
	Bg        string `json:"bg"`
}

// users 修改一条记录
func (u *Config) UpdateOne() *Config {
	n := u.Get()
	if n == nil {
		log.Println("records do not exist")
		return nil
	}
	if u.Name != "" {
		n.Name = u.Name
	}
	if u.Password != "" {
		n.Password = utils.Md5(u.Password)
	}
	if u.Signature != "" {
		n.Signature = u.Signature
	}
	if u.Contact != "" {
		n.Contact = u.Contact
	}
	if u.Bg != "" {
		n.Bg = u.Bg
	}
	sql := "update config set name=?,password=?,signature=?,contact=?,bg=?"
	result, err := common.DB.Exec(sql, n.Name, n.Password, n.Signature, n.Contact, n.Bg)
	if utils.CheckErr(err) {
		return nil
	}
	_, err = result.RowsAffected()
	if utils.CheckErr(err) {
		return nil
	}
	return n
}

// users 查询一条记录,通过ID
func (u *Config) Get() *Config {
	sql := "select name,password,signature,contact,bg from config limit 1"
	var n Config
	err := common.DB.QueryRow(sql).Scan(&n.Name, &n.Password, &n.Signature, &n.Contact, &n.Bg)
	if utils.CheckErr(err) {
		return nil
	}
	return &n
}
